package com.example.service.impl;

import com.example.mapper.*;
import com.example.model.*;
import com.example.service.MachineService;
import com.example.utils.JacksonUtil;
import com.example.utils.ListUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @ClassName SysUserServiceImpl
 * @Description 用户信息Service层接口实现类
 * @Author chengjunyu
 * @Date 2022/1/24 11:13
 * @Version 1.0
 */
@Service
public class MachineServiceImpl implements MachineService {

    @Resource
    public MachineMapper machineMapper;
    @Resource
    public QrcodeProductMapper qrcodeProductMapper;
    @Resource
    public MachineDailySumMapper machineDailySumMapper;
    @Resource
    public VmachineMapper vmachineMapper;

    @Resource
    public ProductProcessMapper productProcessMapper;
    @Resource
    public RecycleQrcodeMapper  recycleQrcodeMapper;

    @Override
    public List<MachineTx> listMachineTxByQrCodes(List<String> qrCodes) {
        if(CollectionUtils.isEmpty(qrCodes)){
            return Collections.emptyList();
        }
        List<Machine> machines = new ArrayList<>();
        ListUtils.slice(qrCodes, 500).forEach(perQrCodes -> {

            List<Machine> innerMachines = machineMapper.listMachineTxByQrCodes(perQrCodes);
            machines.addAll(innerMachines);

        });
        if(CollectionUtils.isEmpty(machines)){
            return Collections.emptyList();
        }
        return machinesToTx(machines);
    }

    /**
     * @param qrCodes
     * @Description 根据二维码查询点胶
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param id
     * @Return com.example.mybatis.model.SysUser
     * @Exception
     */
    @Async
    public List<Machine>  selectMachineResult(List<String> qrCodes)
    {
        return machineMapper.selectMachineResult(qrCodes);
    }
    private List<MachineTx> machinesToTx(List<Machine> machines) {
        List<MachineTx> mtx = new ArrayList<>();
        for (Machine machine : machines) {
            MachineTx tx = new MachineTx();
            tx.setQrcode(machine.getQrcode());
            tx.setMachine_id(machine.getMachine_id());
            tx.setResult(machine.getResult());
            List<Machine_test> mts = testToData(machine.getMachine_test());

            tx.setMachine_test(mts);
            tx.setMachine_value(machine.getMachine_value());
            tx.setMachine_type(machine.getMachine_type());
            tx.setProduct_no(machine.getProduct_no());
            tx.setItem_no(machine.getItem_no());
            tx.setColour_no(machine.getColour_no());
            tx.setLength_type(machine.getLength_type());
            tx.setThickness_type(machine.getThickness_type());
            mtx.add(tx);
        }
        return mtx;
    }

    private List<Machine_test> testToData(String machineTest) {
        List<Machine_test> machineTests = JacksonUtil.json2Bean(machineTest, new TypeReference<List<Machine_test>>() {
        });
        return machineTests;
    }

    /**
     * @param id
     * @Description 根据用户ID查询用户信息
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param id
     * @Return com.example.mybatis.model.SysUser
     * @Exception
     */
    @Override
    public Machine selectMachineById(int id) {
        return machineMapper.selectMachineById(id);
    }

    /**
     * @param qrcode
     * @Description 根据二维码查询
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param id
     * @Return com.example.mybatis.model.SysUser
     * @Exception
     */
    @Override
    public Machine selectMachineByQrcode(String qrcode) {
        return machineMapper.selectMachineByQrcode(qrcode);
    }

    /**
     * @param qrcode
     * @Description 根据二维码查询2
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param id
     * @Return com.example.mybatis.model.SysUser
     * @Exception
     */
    @Override
    public Machine selectMachineByQrcode2(String qrcode) {
        return machineMapper.selectMachineByQrcode2(qrcode);
    }

    /**
     * @param qrcode
     * @Description 根据二维码查询3
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param id
     * @Return com.example.mybatis.model.SysUser
     * @Exception
     */
    @Override
    public Machine selectMachineByQrcode3(String qrcode) {
        return machineMapper.selectMachineByQrcode3(qrcode);
    }

    /**
     * @param qrcode
     * @Description 根据二维码查询3
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param id
     * @Return com.example.mybatis.model.SysUser
     * @Exception
     */

    @Override
    public Machine selectMachineByQrcode4(String qrcode) {
        String  str_x1 ="";
        String  str_x2 ="";
        String  str_absDiff ="";
        String  str_average ="";
        Machine   machine =   machineMapper.selectMachineByQrcode4(qrcode);
        DecimalFormat df = new DecimalFormat("0.00");
      //  String averageStr = df.format(average);

        if (machine!= null) {
            List<Machine_test> mts = testToData(machine.getMachine_test());
            for (Machine_test machineTest :mts) {
                if (machineTest.getTestPoint().equals("距离1") || machineTest.getTestPoint().equals("距离53"))
                    str_x1 = machineTest.getValue();
                if (machineTest.getTestPoint().equals("距离2") || machineTest.getTestPoint().equals("距离54"))
                    str_x2 = machineTest.getValue();
            }
            float num_x1 = Float.parseFloat(str_x1);
            float num_x2 = Float.parseFloat(str_x2);
            //绝对值
            float diff = num_x1 - num_x2;
            float absDiff = Math.abs(diff);
            // 计算两数之和
            float sum = num_x1 + num_x2;
            // 计算平均值
            float average = sum / 2;
            //df.format(num_x1)

            str_x1 =df.format(num_x1).replaceAll("\\.", "");
            str_x2 = df.format(num_x2).replaceAll("\\.", "");
            str_absDiff = df.format(absDiff).replaceAll("\\.", "");
            str_average = df.format(average).replaceAll("\\.", "");
            //X1|X2|绝对值|平均值
           // str.replaceAll("\\.", "")
           // machine.setMachine_test(df.format(num_x1) + "|"+df.format(num_x2)+ "|"+"0"+df.format(absDiff)+ "|"+df.format(average));
            machine.setMachine_test(str_x1 + "|"+str_x2+ "|"+"0"+str_absDiff+ "|"+str_average);
        }
        return machine;
    }

    /**
     * @param machine
     * @Description 根据类型查询
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param id
     * @Return com.example.mybatis.model.SysUser
     * @Exception
     */
    @Override
    public Machine selectMachineByType(Machine machine) {
        return machineMapper.selectMachineByType(machine);
    }

    /**
     * @param qrcode
     * @Description 根据二维码查询点胶
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param id
     * @Return com.example.mybatis.model.SysUser
     * @Exception
     */
    @Override
    public Machine selectMachineDjByQrcode(String qrcode) {
        return machineMapper.selectMachineDjByQrcode(qrcode);
    }

    /**
     * @Description 查询全部用户信息
     * @Author chengjunyu
     * @Date 2022/1/24 11:11
     * @Param * @param
     * @Return java.util.List<com.example.mybatis.model.SysUser>
     * @Exception
     */
    @Override
    public List<Machine> selectMachineAll() {

        return machineMapper.selectMachineAll();
    }

    /**
     * @param machine
     * @Description 新增用户信息
     * @Author chengjunyu
     * @Date 2022/1/24 11:12
     * @Param sysUser
     * @Return int
     * @Exception
     */
    @Async
    @Transactional
    public int insertMachine(Machine machine,List<Machine_test> machine_test_List) {
        try {
            String qrcode =  machine.getQrcode();
            Vmachine vmachine = vmachineMapper.selectVmachine(machine.getMachine_id());
            if (vmachine == null) {
                System.out.println("警告：料号为空，可能会影响数据完整性！");
                return 0;
            }
            QrcodeProduct qrcodeProduct =  qrcodeProductMapper.getProductByQrcode(qrcode,vmachine.getProcessNo());
            if (qrcodeProduct == null) {
                System.out.println("未找到对应的 QrcodeProduct！");
                return 0;
            }

            //通过二维码规则设定带出料号\项目\色号
            machine.setProduct_no(qrcodeProduct.getProductNo());
            machine.setItem_no(qrcodeProduct.getItemNo());
              if (qrcodeProduct.getItemNo().equals("ZS-D-374"))
                machine.setLength_type(calc_length_type374(machine_test_List));
            machine.setColour_no(qrcodeProduct.getColourNo());
            machine.setProcess_no(vmachine.getProcessNo());
            if(machine.getProduct_no().isEmpty() )
            {
                System.out.println("警告：料号为空，可能会影响数据完整性！");
                return 0; // 提前返回，表示插入失败
            }

            ///回收二维码
            ProductProcess productProcess = productProcessMapper.selectProductProcess(machine.getProduct_no(),machine.getProcess_no());
           if (productProcess.isUseFlag())
            {
                RecycleQrcode  recycleQrcode =   recycleQrcodeMapper.selectRecycleQrcodeByQrcode(qrcode);
                machine.setQrcode(recycleQrcode.getNewQrcode());
            }
           //执行插入
            int count = machineMapper.insertMachine(machine);
            // if (count > 0)
            // {
            //  updateMachineDailySum(machine);
            //}
            return   count;
        } catch (Exception e) {
            // logger.error("插入机器信息时发生异常: ", e);
            return 0;
        }

    }

    /**
     * @param machine
     * @Description 更新或插入汇总数据
     * @Author chengjunyu
     * @Date 2022/1/24 11:12
     * @Param sysUser
     * @Return int
     * @Exception
     */
@Async
public void updateMachineDailySum(Machine machine)
{
    if (machine == null || machine.getItem_no() == null || machine.getItem_no().equals("")) {
      //  System.out.println("值为空或者 null，退出方法");
        return;
    }
        LocalDate currentDate = LocalDate.now();
        String currentDateString = currentDate.toString();
        LocalDate startDate = LocalDate.parse(currentDateString);
        LocalDate endDate = startDate.plusDays(1);
        java.sql.Date sqlStartDate = java.sql.Date.valueOf(startDate);
        java.sql.Date sqlEndDate = java.sql.Date.valueOf(endDate);
        java.sql.Date sqlCurrentDate = java.sql.Date.valueOf(currentDate);

        int totalCount = machineMapper.countByItemNoAndDate(machine.getItem_no(),machine.getProduct_no(),machine.getMachine_id(),machine.getResult(), sqlStartDate,sqlEndDate);
        if (totalCount > 0)
        {
            MachineDailySum dailySum = machineDailySumMapper.findByItemNoAndDate(machine.getItem_no(),machine.getProduct_no(),machine.getMachine_id(),machine.getResult(),sqlCurrentDate);
            if (dailySum == null) {
                dailySum = new MachineDailySum();
                dailySum.setItemNo(machine.getItem_no());
                dailySum.setProductNo(machine.getProduct_no());
                dailySum.setResult(machine.getResult());
                dailySum.setMachineId(machine.getMachine_id());
                dailySum.setSumDate(sqlCurrentDate);
                dailySum.setTotalCount(totalCount);
                machineDailySumMapper.insertMachineDailySum(dailySum);
            } else {
                dailySum.setTotalCount(totalCount);
                machineDailySumMapper.updateMachineDailySum(dailySum);
            }
        }
}
    /**
     * @param machine
     * @Description 新增用户信息
     * @Author chengjunyu
     * @Date 2022/1/24 11:12
     * @Param sysUser
     * @Return int
     * @Exception
     */
    @Async
    public int insertMachineResult(Machine machine) {
        return machineMapper.insertMachineResult(machine);
    }
    /**
     * @param ccddata
     * @Description 修改用户信息
     * @Author chengjunyu
     * @Date 2022/1/24 11:12
     * @Param sysUser
     * @Return int
     * @Exception
     */
    @Override
    public int updateMachine(Machine ccddata) {
        return machineMapper.updateMachine(ccddata);
    }

    /**
     * @param id
     * @Description 删除用户信息
     * @Author chengjunyu
     * @Date 2022/1/24 11:12
     * @Param id
     * @Return int
     * @Exception
     */
    @Override
    public int deleteMachineById(int id) {
        return machineMapper.deleteMachineById(id);
    }


    /**
     * [{"TestPoint":"Q1","Value":"0.349"},{"TestPoint":"Q2","Value":"0.359"},{"TestPoint":"Q3","Value":"0.351"}]
     * @param machine_datalist
     * @return
     */
    private String calc_length_type374(List<Machine_test> machine_datalist)
    {
        AtomicReference<Float> Q1_length = new AtomicReference<>((float) 0);
        AtomicReference<Float> Q2_length = new AtomicReference<>((float) 0);
        AtomicReference<Float> Q3_length = new AtomicReference<>((float) 0);
        String length_type = "";

        //Q1  {"TestPoint":"Q1","Value":"0.349"}
        List<Machine_test> mid_resultList = machine_datalist.stream().filter(Machine_test -> Objects.equals(Machine_test.getTestPoint(),"Q1")).collect(Collectors.toList());
        mid_resultList.stream().forEach(machine_test ->{
            Q1_length.set(Float.parseFloat(machine_test.getValue()));
            // System.out.println(machine_data.getTestPoint()+"-"+machine_data.getValue());
        });
        //Q2  {"TestPoint":"Q2","Value":"0.359"}
        List<Machine_test> left_resultList = machine_datalist.stream().filter(Machine_test -> Objects.equals(Machine_test.getTestPoint(),"Q2")).collect(Collectors.toList());
        left_resultList.stream().forEach(machine_test ->{
            Q2_length.set(Float.parseFloat(machine_test.getValue()));
            // System.out.println(machine_data.getTestPoint()+"-"+machine_data.getValue());
        });
        //Q3  {"TestPoint":"Q3","Value":"0.351"}
        List<Machine_test> right_resultList = machine_datalist.stream().filter(Machine_test -> Objects.equals(Machine_test.getTestPoint(),"Q3")).collect(Collectors.toList());
        right_resultList.stream().forEach(machine_test ->{
            Q3_length.set(Float.parseFloat(machine_test.getValue()));
            // System.out.println(machine_data.getTestPoint()+"-"+machine_data.getValue());
        });
        if (   ((0.320f <= Q1_length.get()) && (Q1_length.get() <= 0.360f)) //S
                &&((0.320f <= Q2_length.get()) && (Q2_length.get() <= 0.360f))//S
                &&((0.320f <= Q3_length.get()) && (Q3_length.get() <= 0.360f))//S

                || ((0.320f <= Q1_length.get()) && (Q1_length.get() <= 0.360f))//S
                &&((0.320f <= Q2_length.get()) && (Q2_length.get() <= 0.360f))//S
                &&((0.361f <= Q3_length.get()) && (Q3_length.get() <= 0.400f))//L

                || ((0.320f <= Q1_length.get()) && (Q1_length.get() <= 0.360f))//S
                &&((0.361f <= Q2_length.get()) && (Q2_length.get() <= 0.400f))//L
                &&((0.320f <= Q3_length.get()) && (Q3_length.get() <= 0.360f))//S

                || ((0.361f <= Q1_length.get()) && (Q1_length.get() <= 0.400f))//L
                &&((0.320f <= Q2_length.get()) && (Q2_length.get() <= 0.360f))//S
                &&((0.320f <= Q3_length.get()) && (Q3_length.get() <= 0.360f))//S
        )
        {
            length_type = "a";
        }
        else if( ((0.361f <= Q1_length.get()) && (Q1_length.get() <= 0.400f)) //L
                &&((0.361f <= Q2_length.get()) && (Q2_length.get() <= 0.400f))//L
                &&((0.320f <= Q3_length.get()) && (Q3_length.get() <= 0.360f))//S

                || ((0.361f <= Q1_length.get()) && (Q1_length.get() <= 0.400f))//L
                &&((0.320f <= Q2_length.get()) && (Q2_length.get() <= 0.360f))//S
                &&((0.361f <= Q3_length.get()) && (Q3_length.get() <= 0.400f))//L

                || ((0.320f <= Q1_length.get()) && (Q1_length.get() <= 0.360f))//S
                &&((0.361f <= Q2_length.get()) && (Q2_length.get() <= 0.400f))//L
                &&((0.361f <= Q3_length.get()) && (Q3_length.get() <= 0.400f))//L

                || ((0.361f <= Q1_length.get()) && (Q1_length.get() <= 0.400f))//L
                &&((0.361f <= Q2_length.get()) && (Q2_length.get() <= 0.400f))//L
                &&((0.361f <= Q3_length.get()) && (Q3_length.get() <= 0.400f))//L
        )
        {
            length_type = "c";
        }

        return length_type;
    }
/*
    @Override
    public String calc_product(String str_qrcode)
    {
        String str_product = "";

        if ((str_qrcode.length() == 26) || (str_qrcode.length() == 27))
        {  //二维码前十位判断项目
            // str_item 010:1031010090,1031010120
            // 020:1031010101,1031010121
            //010的料号(1031010090,1031010120)   1031010101
            str_product  = str_qrcode.substring(0, 10);
        }
        if ((str_qrcode.length() == 15) || (str_qrcode.length() == 16))
        {   //二维码第3位判断项目  C/F  第六位  B/L
            //  010 :C   白色B: 1031010090   绿色L: 1031010120
            //  020 :F   白色B: 1031010101   绿色L: 1031010121

            if ((str_qrcode.substring(2, 3).equals("C")) && (str_qrcode.substring(5, 6).equals("B")))
                str_product = "1031010090";//  010 :C   白色B: 1031010090

            if ((str_qrcode.substring(2, 3).equals("C")) && (str_qrcode.substring(5, 6).equals("L")))
                str_product = "1031010120";//  010 :C   绿色L: 1031010120

            if ((str_qrcode.substring(2, 3).equals("F")) && (str_qrcode.substring(5, 6).equals("B")))
                str_product = "1031010101";//  020 :F   白色B: 1031010101

            if ((str_qrcode.substring(2, 3).equals("F")) && (str_qrcode.substring(5, 6).equals("L")))
                str_product = "1031010121";//  020 :F   绿色L: 1031010121
        }
        return str_product;
    }

    @Override
    public String calc_item(String str_product)
    {
        String str_item = "";
        //  010 :C   白色B: 1031010090   绿色L: 1031010120
        //  020 :F   白色B: 1031010101   绿色L: 1031010121
        if (str_product.equals("1031010090"))
            str_item = "ZS-D-010";
        if (str_product.equals("1031010120"))
            str_item = "ZS-D-010";
        if (str_product.equals("1031010101"))
            str_item = "ZS-D-020";
        if (str_product.equals("1031010121"))
            str_item = "ZS-D-020";
        return str_item;
    }
    @Override
    public String calc_colour(String str_product)
    {
        String str_colour = "";
        //  010 :C   白色B: 1031010090   绿色L: 1031010120
        //  020 :F   白色B: 1031010101   绿色L: 1031010121
        if (str_product.equals("1031010090"))
            str_colour = "B";
        if (str_product.equals("1031010120"))
            str_colour = "L";
        if (str_product.equals("1031010101"))
            str_colour = "B";
        if (str_product.equals("1031010121"))
            str_colour = "L";
        return str_colour;
    }
    */

}
